using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using Framework.Library.Core.Provider.Log;

namespace Framework.Library.Core.Utils.IO
{
    public class Serializer<T>
    {

        public void SerializeObject(string filename, T objectToSerialize)
        {
            try
            {
                using (var stream = File.Open(filename, FileMode.Create))
                {
                    var bFormatter = new BinaryFormatter();
                    bFormatter.Serialize(stream, objectToSerialize);
                    stream.Close();
                }
            }
            catch (Exception exception)
            {
                Logger.Error(exception);
            }
        }

        public T DeSerializeObject(string filename)
        {
            try
            {
                if (File.Exists(filename))
                {
                    using (var stream = File.Open(filename, FileMode.Open))
                    {
                        var bFormatter = new BinaryFormatter();
                        var objectToSerialize = (T)bFormatter.Deserialize(stream);
                        stream.Close();
                        return objectToSerialize;
                    }
                }
            }
            catch (Exception exception)
            {
                Logger.Error(exception);
            }
            return default(T);
        }
    }
}